#fastapi做的文件服务器
#python3 -m uvicorn fastapi0:app --host "0.0.0.0" --port 82 --reload
from fastapi import FastAPI
from fastapi import FastAPI,Form
from starlette.responses import HTMLResponse
from starlette.responses import RedirectResponse
import uvicorn
from pyecharts import options as opts
import json
import os
#from pyecharts.components import Table
from pyecharts.options import ComponentTitleOpts
from tinydb import TinyDB, Query
from fastapi import Cookie, FastAPI
from typing import Optional
from starlette.responses import Response
import dirs
from fastapi import FastAPI, File, UploadFile
from openpyxl import load_workbook
from starlette.staticfiles import StaticFiles
def tab_html(title,headers0,rows):
    rights=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+str(item)+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    rows_new=rows.copy()
    rows.reverse()
    #print(rows)
    print('***********************************')
    lenrow=len(rows)
    for row in range(len(rows_new)):
        body=body+'<tr>'
        for col in range(len(rows_new[row])):
            #print(col)
            if rights[col]==1:
               
           
                itemx='<a href="?col={}&row={}">{}</a>'.format(col+1,lenrow-row+1,str(rows[row][col]))
            else:
            
                itemx=str(rows[row][col])
            #print(col,row,itemx)
            body=body+'<td>'+itemx+'</td>'
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body

#wb = load_workbook(filename = 'demo.xlsx')
#sheet_ranges = wb['range names']
#ws = wb.active
#print(ws.cell(row=4, column=2).value)

 

app = FastAPI()
location='./static'
app.mount('/static', StaticFiles(directory=location), name='static') 


#首页，默认跳转到表单列表
@app.get("/")

def home():
   
    return RedirectResponse(url='test')
    return 'hello'
form0='''
        <form action="?" method="get">
  <p>修改值: <input type="text" name="value" value="{value}" style="width:400px;"></p>
  <input type="hidden" name="col" value="{col}">
  <input type="hidden" name="row" value="{row}">

  <input type="submit" value="Submit" />
</form>
'''

@app.get("/items/{item_id}")
def read_item(item_id: Optional[str] = None, row: Optional[str] = None,col: Optional[str] = None,value: Optional[str] = None):
    #print(item_id)
    wb = load_workbook(filename = './static/'+item_id)
    #print(filename)
    #print(wb)
#sheet_ranges = wb['range names']
    ws = wb.active
    if value:
        #pass
        ws.cell(row=int(row),column=int(col),value=value)
        wb.save(filename = './static/'+item_id)
        return RedirectResponse('?')
    elif col:

        return HTMLResponse(content=form0.format(value=ws.cell(row=int(row),column=int(col)).value,col=col,row=row))
    else:

   
        #print(ws[c+r].value)
        #print(ws.values)
        rows=[]
        data=ws.values
        #data0=data[1:]
        #print(list(data))
        #heraders=list(data)[0]
        i=0
        for row in ws.values:
            if i==0:
                headers=row
            else:
            #print(list(row))
                rows.append(list(row))
            i=i+1
           #for value in row:
             #print(value)
            #print(row)
            #a=input('hello')
        list_new=[]
        for item in headers:
            list_new.append('*')
        rows.append(list_new)
            #print(ws.values[0])
        return HTMLResponse(content=dirs.start+tab_html('hello',headers,rows))
        #return {"item_id": item_id,'c':c, "r": r, 'result':ws[c+r].value}
@app.get("/login")
async def login(response: Response,q: str=None):
    content='''

<body>
<h4>百度一下</h4>
<form name="input" action="test" method="get">
<input type="text" name="q">
<input type="submit" value="搜索">
</form>

</body>

    '''

    return HTMLResponse(content=content)
@app.get("/test1/")

def create_cookie(response: Response,q: str=None):
    value=q+"@gi-de.com"
    userlist=['abc@gi-de.com']
    print(value)
    if value in userlist:

        response.set_cookie(key="username", value=q+"@xxxx.com", expires=100000000)
   

        return "已登录，请关闭重新打开"
    else:
        return "未获授权，请联系管理员"

#test
@app.get("/test")
def test():

    return HTMLResponse(content='<dir><a href="/upload">上传excel表</a></dir><dir><a href="/static">查看历史报告</a></dir>')

#static
@app.get("/static")
def static0(item_id: str=None,q: str = ''):
    location='./static'
    print('q:',q)
    #listfiles=os.listdir(location)
    def web(locationx):
        print('locationx:',locationx)
        if os.path.isfile(locationx):
            #return RedirectResponse(url=locationx)
            return '<dir><a href={}>{}</a></dir>'.format(locationx,locationx).replace('//','/')
        z=''

        for item in os.listdir(locationx):
            print(item,locationx+item)
            if os.path.isfile(locationx+'/'+item):
                print('isfile',locationx+'/'+item)
                z=z=z+'<dir><a href={}>{}</a></dir>'.format('/'+'items'+'/'+item,item)
            elif os.path.isdir(locationx+'/'+item):
                z=z=z+'<dir><a href={}>{}</a></dir>'.format('?q='+q+'/'+item,item)
        z=z.replace('//','/')
        return z


    title='''
    <div class="jumbotron">
      <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{}</h3>
      '''

    return HTMLResponse(content=dirs.start+title.format(q)+web(location+'/'+q))

###############上传文件###############

@app.post("/uploadfiles/")
async def create_upload_files(
    file: UploadFile = File(...)
):
    #return {"filenames": [file.filename for file in files]}
    #contents = await files[0].read().decode('utf8')
    contents = file.file.read()
    name0=file.filename
    with open('static/'+name0,'wb') as f:
        f.write(contents)
    #return files[0].filename, files[0].content_type
        content = """
<body>
<a href="/static/{}" title="转到CSS5主页">上传完成，下载链接请右键复制</a>
</body>
 """.format(name0)
    return HTMLResponse(content=content)


@app.get("/upload")
async def upload():
    content = """
<body>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="file" type="file" multiple>
<input type="submit">
</form>
</body>
 """
    return HTMLResponse(content=content)
############################################

if __name__ == "__main__":

    uvicorn.run(app, host="0.0.0.0",port=80,log_level="info")
